package com.sgcc.epri.dcloud.service;

import cn.hutool.core.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@Service
public class AutoCreateTablePartition {

    private final Logger log =  LoggerFactory.getLogger(this.getClass());

    @Qualifier("dmDataSource")
    @Autowired
    private DataSource dataSource;

    /**
     * 完整率相关指标表，二级详情指标表分区创建任务
     */
//    @Scheduled(cron = "0/30 * * * * ? ")
    @Scheduled(cron = "0 0 12 * * ? ")
    public void sg_access_integrity_content_very(){
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();

            String tomorrow = DateUtil.tomorrow().toString().substring(0,10);

            String sql = String.format("ALTER TABLE dky_db.sg_access_integrity_content_very ADD PARTITION %s VALUES LESS THAN ('%s')",
                    "p"+tomorrow.replaceAll("-",""), tomorrow);

            stmt.executeUpdate(sql);
            log.info("sg_access_integrity_content_very（完整率相关指标表，二级详情指标表分区）表分区创建成功！");

            stmt.close();
            conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
